package com.fcat.common.user.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fcat.springboot.core.util.SpringbootUtil;
import com.fcat.springboot.mybatis.controller.TsuantoneBaseController;
import com.fcat.base.common.util.ArrayUtil;
import com.fcat.springboot.mybatis.util.JsonUtil;
import com.fcat.base.common.util.StrUtil;
import com.fcat.common.user.entity.*;
import com.fcat.common.user.service.*;
import com.fcat.common.user.vo.PermissionVO;
import com.fcat.common.user.vo.RoleGroupVO;
import com.fcat.common.user.vo.UserRoleVO;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("role")
public class RoleController extends TsuantoneBaseController<RoleService, Role, Integer> {
    @Autowired
    private RoleGroupService roleGroupService;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private PermissionService permissionService;
    @Autowired
    private UserService userService;

    private final String defaultRoleGroupName = "系统默认角色组";
    private final Long defaultRoleGroupId = 1L;


    @ApiOperation("获取角色树")
    @GetMapping("/getRoleTree")
    public JSONObject getRoleTree(String roleName) {
        String username = SpringbootUtil.parseToken().getUsername();
        JSONObject resultJson = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        List<RoleGroupVO> roleGroupVOList = roleGroupService.getTree(roleName,username, SpringbootUtil.parseToken().getCompanyId());
        if (CollectionUtils.isEmpty(roleGroupVOList)) return JsonUtil.getFailJsonObject("没有角色组");
        for (RoleGroupVO roleGroupVO : roleGroupVOList) {
            JSONObject roleGroupVOJson = new JSONObject();
            roleGroupVOJson.put("roleGroupId", roleGroupVO.getId());
            roleGroupVOJson.put("title", roleGroupVO.getName());
            roleGroupVOJson.put("children", roleGroupVO.getRoleVOList());
            jsonArray.add(roleGroupVOJson);
        }
        resultJson.put("list", jsonArray);
        return JsonUtil.getSuccessJsonObject(resultJson);
    }

    @ApiOperation("编辑角色组")
    @PostMapping("/updateRoleGroup")
    public JSONObject updateRoleGroup(@RequestBody RoleGroup roleGroup) {
        Integer num = -1;
        if (roleGroup == null) return JsonUtil.getFailJsonObject("请选择角色组");
        if (roleGroup.getId() == defaultRoleGroupId) return JsonUtil.getFailJsonObject("默认角色组不允许更改");
        if (StrUtil.isBlank(roleGroup.getName())) return JsonUtil.getFailJsonObject("请输入角色组名称");
        if (roleGroup.getName().equals(defaultRoleGroupName)) return JsonUtil.getFailJsonObject("不允许修改默认角色组");
        roleGroup.setUpdateTime(new Date());
        num = roleGroupService.updateSelectiveById(roleGroup);
        if (num == 1) return JsonUtil.getSuccessJsonObject();
        return JsonUtil.getFailJsonObject("修改失败");
    }


    @ApiOperation("新增角色组")
    @PostMapping("/addRoleGroup")
    public JSONObject addRoleGroup(@RequestParam("roleGroupName") String roleGroupName) {
        if (StrUtil.isBlank(roleGroupName)) return JsonUtil.getFailJsonObject("请输入角色名称");
        if (roleGroupName.equals(defaultRoleGroupName)) return JsonUtil.getFailJsonObject("不能输入默认角色组名称");
        String username = SpringbootUtil.parseToken().getUsername();
        Long companyId = SpringbootUtil.parseToken().getCompanyId();
        Integer num = -1;
        RoleGroup roleGroup = new RoleGroup();
        roleGroup.setName(roleGroupName);
        roleGroup.setCompanyId(companyId);
        roleGroup.setUsername(username);
        num = roleGroupService.insertSelective(roleGroup);
        if (num != 1) return JsonUtil.getFailJsonObject("新增失败");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", roleGroup.getId());
        return JsonUtil.getSuccessJsonObject(jsonObject);
    }


    @ApiOperation("新增角色")
    @PostMapping("/addRole")
    public JSONObject addRole(@RequestBody Role role) {
        String username = SpringbootUtil.parseToken().getUsername();
        Long companyId = SpringbootUtil.parseToken().getCompanyId();
        Integer num = -1;
        if (role == null) return JsonUtil.getFailJsonObject("请选择角色");
        if (StrUtil.isBlank(role.getName())) return JsonUtil.getFailJsonObject("请输入角色名");
        if (role.getRoleGroupId() == null) return JsonUtil.getFailJsonObject("请选择角色组");
        if (role.getRoleGroupId().equals(defaultRoleGroupId)) return JsonUtil.getFailJsonObject("不能添加系统默认角色");
        //查询所有系统默认角色
        List<String> defaultRoleNameList = bsi.getSystemDefaultRoleName();
        if (defaultRoleNameList.contains(role.getName())) return JsonUtil.getFailJsonObject("系统默认角色名不允许创建");
        role.setCompanyId(companyId);
        role.setUsername(username);
        num = bsi.insertSelective(role);
        if (num != 1) return JsonUtil.getFailJsonObject("新增失败");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", role.getId());
        jsonObject.put("roleGroupId", role.getRoleGroupId());
        return JsonUtil.getSuccessJsonObject(jsonObject);
    }


    @ApiOperation("查看所有角色")
    @GetMapping("/getRoleList")
    public JSONObject getRoleList() {
        String username = SpringbootUtil.parseToken().getUsername();
        Long companyId = SpringbootUtil.parseToken().getCompanyId();
        Map<String, Object> map = new HashMap<>();
        map.put("username", username);
        List<Long> list = new ArrayList<>();
        list.add(companyId);
        if (bsi.getUserIsAdmin(map)) list.add(Long.valueOf(0));
        map.put("list", list);
        List<Role> roles = bsi.getListByCompnayIdAndUsername(map);
        JSONArray jsonArray = new JSONArray();
        if (CollectionUtils.isEmpty(roles)) return JsonUtil.getFailJsonObject("没有角色");
        for (Role item : roles) {
            JSONObject itemJson = new JSONObject();
            itemJson.put("roleId", item.getId());
            itemJson.put("roleName", item.getName());
            jsonArray.add(itemJson);
        }
        return JsonUtil.getSuccessJsonObject(jsonArray);
    }

    @ApiOperation("查看所有角色组")
    @GetMapping("/getRoleGroupList")
    public JSONObject getRoleGroupList() {
        String username = SpringbootUtil.parseToken().getUsername();
        Long companyId = SpringbootUtil.parseToken().getCompanyId();
        Map<String, Object> map = new HashMap<>();
        map.put("companyId", companyId);
        map.put("username", username);
        List<RoleGroup> roleGroups = roleGroupService.getListByCompnayIdAndUsername(map);
        JSONArray jsonArray = new JSONArray();
        if (ArrayUtil.isEmpty(roleGroups)) return JsonUtil.getFailJsonObject("无角色组请添加角色组");
        for (RoleGroup item : roleGroups) {
            if (item.getId() == 1) continue;
            JSONObject itemJson = new JSONObject();
            itemJson.put("roleGroupId", item.getId());
            itemJson.put("roleGroupName", item.getName());
            jsonArray.add(itemJson);
        }
        if (ArrayUtil.isEmpty(jsonArray)) return JsonUtil.getFailJsonObject("无角色组请添加角色组");
        return JsonUtil.getSuccessJsonObject(jsonArray);
    }

    @ApiOperation("删除角色")
    @PostMapping("/delRole")
    public JSONObject delRole(@RequestParam("id") Long id) {
        if (id == null) return JsonUtil.getFailJsonObject("请选择要删除的角色");
        //查询出系统默认角色的list
        List<Long> roleList = bsi.getSystemDefaultRoleId();
        if (roleList.contains(id)) return JsonUtil.getFailJsonObject("系统默认角色不允许删除");
        UserRole userRole = new UserRole();
        userRole.setRoleId(id);
        List<UserRole> userRoleList = userRoleService.selectList(userRole);
        if (!ArrayUtil.isEmpty(userRoleList)) return JsonUtil.getFailJsonObject("当前角色已绑定用户无法删除");
        Integer num = bsi.deleteById(id);
        if (num == 1) return JsonUtil.getSuccessJsonObject();
        return JsonUtil.getFailJsonObject("删除失败");
    }

    @ApiOperation("批量删除角色")
    @PostMapping("/delRoles")
    public JSONObject delRoles(@RequestParam("ids") String ids) {
        if (ids == null) return JsonUtil.getFailJsonObject("请选择角色");
        List<Long> longs = StrUtil.getLongListByString(ids,",");
        if (ArrayUtil.isEmpty(longs)) return JsonUtil.getFailJsonObject("请选择角色");
        //查询出系统默认角色的list
        List<Long> roleList = bsi.getSystemDefaultRoleId();
        for (Long aLong : longs) {
            if (roleList.contains(aLong))
                return JsonUtil.getFailJsonObject("无法删除系统默认角色");
        }
        List<UserRole> userRoleList = userRoleService.getListByRoleids(longs);
        if (!ArrayUtil.isEmpty(userRoleList)) return JsonUtil.getFailJsonObject("当前角色中有角色在绑定状态中,无法删除");
        Integer num = bsi.deleteByIds(longs);
        if (num > 1) return JsonUtil.getSuccessJsonObject();
        return JsonUtil.getFailJsonObject("删除失败");
    }


    /**
     * flag=1 查询除了管理以外  传查询全部
     *
     * @param flag
     * @return
     */
    @ApiOperation("查询当前用户的角色")
    @GetMapping("/getListByUsername")
    public JSONObject getListByUsername( Integer flag) {
        User user = userService.getUserByUsername(SpringbootUtil.parseToken().getUsername());
        Map<String, Object> map = new HashMap<>();
        map.put("companyId", user.getCompanyId());
        map.put("flag", flag);
        JSONArray result = new JSONArray();
        bsi.getListByUser(map).forEach(item -> {
            JSONObject json = new JSONObject();
            json.put("id", item.getId().toString());
            json.put("name", item.getName());
            result.add(json);
        });
        return JsonUtil.getSuccessJsonObject(result);
    }

    @ApiOperation("查看角色权限")
    @GetMapping("/getPermissionListByRoleId")
    public JSONObject getPermissionListByRoleId(@RequestParam("roleId") Long roleId) {
        //查询所有权限
        List<PermissionVO> permissionVOList = permissionService.getAll();
        //查询出现在的角色拥有的权限
        List<Permission> permissionList = permissionService.getPermissionByRoleId(roleId);
        //用于获取所有拥有的权限id
        List<Long> idList = new ArrayList<>();
        //获取所有拥有的权限id
        for (Permission permission : permissionList) {
            idList.add(permission.getId());
        }
        //进行对象赋值
        for (PermissionVO permissionVO : permissionVOList) {
            permissionVO.setFlag(0);
            if (idList.contains(permissionVO.getId())) {
                permissionVO.setFlag(1);
            }
        }
        //递归生成树
        List<PermissionVO> resultList = permissionService.getTree(permissionVOList, 0L);
        return JsonUtil.getSuccessJsonObject(resultList);
    }

    @ApiOperation("修改角色权限")
    @PostMapping("updateRolePermission")
    public JSONObject updateRolePermission(@RequestBody JSONObject jsonObject) {
        Long roleId = jsonObject.getLong("roleId");
        if (roleId == null) return JsonUtil.getFailJsonObject("pleaseSelectRole");
        //查询出系统默认角色的list
        List<Long> roleList = bsi.getSystemDefaultRoleId();
        if (roleList.contains(roleId)) return JsonUtil.getFailJsonObject("系统默认角色不允许修改");
        //权限数组
        String permissionIds = jsonObject.getString("permissionIds");
        if (StrUtil.isBlank(permissionIds)) return JsonUtil.getFailJsonObject("请保留基础权限");
        List<Long> longs = StrUtil.getLongListByString(permissionIds,",");
        if (ArrayUtil.isEmpty(longs)) return JsonUtil.getFailJsonObject("请保留基础权限");
        boolean flag = bsi.updateRole(SpringbootUtil.getCurrentToken(), roleId, longs);
        return JsonUtil.getSuccessJsonObject();
    }

    @ApiOperation("获取当前单位下拥有系统管理员权限的账户")
    @GetMapping("getByCompanyIdAndId")
    public JSONObject getByCompanyIdAndId(@RequestParam("id")Long id) {
        List<UserRoleVO> systemUserVo = bsi.getByCompanyIdAndId(SpringbootUtil.parseToken().getCompanyId(),id);
        return JsonUtil.getSuccessJsonObject(systemUserVo);
    }


}